package myservice.android.activities;

import java.util.ArrayList;
import java.util.Calendar;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.PopupMenu;
import myservice.android.utilities.Record;
import myservice.android.utilities.RecordAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class PersonCallListActivity extends BaseActivity {
	
	private Button addCallButton;
	private ArrayList<Record> callData;
	private Spinner sortCallsSpinner;
	private ImageView personIcon;
	private TextView personName;
	private ListView callList;
	private TextView noCallsDefinedText;
	private RecordAdapter callAdapter;
	
	private long personId;
	
	@Override
	protected void initializeLayoutIdAndTitle() {
		
		layoutId = R.layout.person_calls;
		activityTitle = Global.res.getString(R.string.title_calls);
		
	}

	@Override
	protected void retrieveViews() {
		
        addCallButton = (Button) findViewById(R.id.addCallButton);    
        sortCallsSpinner = (Spinner) findViewById(R.id.sort_spinner);
        personIcon = (ImageView) findViewById(R.id.personIcon);
        personName = (TextView) findViewById(R.id.nameText);
        callList = (ListView) findViewById(R.id.callsList);
        noCallsDefinedText = (TextView) findViewById(R.id.noCallsMessage);
		
	}

	@Override
	protected void loadActivityParameters() {

		personId = activityParameters.getLong("person_id");
		
	}

	@Override
	protected void assignListeners() {

    	personIcon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();			
			}
			
    	});
    	
    	personName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();			
			}
			
    	});    	
        
        addCallButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				final Dialog dialog = new Dialog(PersonCallListActivity.this);
				dialog.setContentView(R.layout.add_call_biblestudy_dialog);
				dialog.setTitle(Global.res.getString(R.string.title_add_new_call));
				
				Button saveButton = (Button) dialog.findViewById(R.id.saveButton);				
				Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
				final CheckBox bibleStudyCheckbox = (CheckBox) dialog.findViewById(R.id.bibleStudyConductedCheckbox);
				final EditText commentsField = (EditText) dialog.findViewById(R.id.commentsField);
				
				saveButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {				
						
						Calendar today = Calendar.getInstance();
						
						int bibleStudy = 0;
						if (bibleStudyCheckbox.isChecked())
							bibleStudy = 1;						
						
						Database.execSQL("INSERT INTO calls (callid,date,month,year,personid,territoryid,comments,biblestudy,timestamp) VALUES ("+Database.getUniqueRowId("calls")+
								         ","+today.get(Calendar.DATE)+","+today.get(Calendar.MONTH)+","+today.get(Calendar.YEAR)+","+personId+
								         ",0,'"+Global.fixText(commentsField.getText())+"',"+bibleStudy+","+Global.getTimeStamp()+")");	
						dialog.dismiss();
						updateList();
					}			
				});
				
				cancelButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();				
					}			
				});		
				
				dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);								
				dialog.show();					
															
			}
        });       
                
        sortCallsSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long id) {
				updateList();				
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
        	
        });
		
	}		                    
    
	private void updateList() {		
		
		PopupMenu.createPopupMenu(this);
		PopupMenu.menuSection3.setVisibility(View.GONE);
		PopupMenu.menuSection4.setVisibility(View.GONE);
		
		callData = new ArrayList<Record>();
		
		String sql = "SELECT date,month,year,callid,comments,biblestudy FROM calls WHERE timestamp<>"+Global.TIMESTAMP_DELETED+" AND personid="+personId;
		if (sortCallsSpinner.getSelectedItemPosition()==1)
			sql=sql+" ORDER BY year,month,date";
		else
			sql=sql+" ORDER BY year DESC,month DESC,date DESC";
		
    	Cursor cursor = Database.select(sql);    		
    	
    	boolean noCallsDefined = true;

    	while (cursor.moveToNext()) {
    		noCallsDefined=false;
    		Record rec = new Record();
    		rec.id=cursor.getInt(cursor.getColumnIndex("callid"));
    		rec.firstLine=Global.getFormattedDate(cursor.getInt(cursor.getColumnIndex("year")), cursor.getInt(cursor.getColumnIndex("month")), cursor.getInt(cursor.getColumnIndex("date")));
    		rec.secondLine=cursor.getString(cursor.getColumnIndex("comments"));
    		rec.status=cursor.getInt(cursor.getColumnIndex("biblestudy"));    		
    		callData.add(rec);
    	}	
    	cursor.close();    	 
    	
    	if (noCallsDefined==true) {
    		noCallsDefinedText.setVisibility(View.VISIBLE);
    	}
    	else {
    		noCallsDefinedText.setVisibility(View.GONE);
    	}
    	
        callAdapter = new RecordAdapter(this, R.layout.list_row, callData, 1);
        callList.setAdapter(callAdapter);
        
        callList.setOnItemLongClickListener(new OnItemLongClickListener () {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				final long cid = callData.get(position).id;
				
				PopupMenu.menuHeading.setText(callData.get(position).firstLine);
				
				PopupMenu.menuOption1.setText(Global.res.getString(R.string.menuitem_modify_call));		
				PopupMenu.menuOption2.setText(Global.res.getString(R.string.menuitem_delete_call));						
				
				PopupMenu.menuOption1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						clickCall(cid);				
					}					
				});
				
				PopupMenu.menuOption2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(PersonCallListActivity.this);
						alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
						alertDialogBuilder
							.setMessage(Global.res.getText(R.string.message_delete_call_confirmation))
							.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									Database.deleteCall(cid);
									updateList();
								}
							  })
							.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});
				 
						AlertDialog alertDialog = alertDialogBuilder.create();
						alertDialog.show();					
					}					
				});										
				
				PopupMenu.showMenu(view);				
				
				return true;
			}
        	
        });        
        
        
        callList.setOnItemClickListener(new OnItemClickListener() {
        	
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				 
				clickCall(callData.get(position).id);
			     				
			}			
        	
        });
    	
	}  
	
	private void clickCall(long cid) {
		 Intent i = new Intent(getApplicationContext(),CallActivity.class);
	     i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
	     i.putExtra("call_id",cid);			     
	     startActivity(i);		
	}	
	
	@Override
	protected void updateUi() {

    	Cursor cursor = Database.select("SELECT name FROM persons WHERE personid="+personId);
    	cursor.moveToNext();
    	personName.setText(cursor.getString(cursor.getColumnIndex("name")));
    	cursor.close();
    	
    	updateList();
		
	}	

}
